<script lang="ts" setup>
import type { StateType } from '~/types'
import { changeDirection, initGame, replayGame, startGame } from '~/snake'
const state = reactive<StateType>({
  map: [],
})
const isLive = ref(1)
const startMS = ref(0)
const start = () => {
  startMS.value = Date.now()
  startGame()
}
const replay = () => {
  startMS.value = Date.now()
  replayGame()
}
const change = (direction: string) => {
  changeDirection(direction)
}
const now = $(useNow())
const countdown = $computed(() => {
  if (isLive.value === 1)
    return 0

  else
    return Math.round((+now - startMS.value) / 1000)
},
)
initGame(state.map, isLive)
</script>

<template>
  <div>
    Snake
  </div>
  <div flex="~ gap-20" justify-center p5>
    <el-button v-if="isLive === 1" type="primary" size="large" @click="start">
      Start
    </el-button> <el-button v-else type="primary" size="large" @click="replay">
      New Game
    </el-button>

    <div>
      <div i-mdi-clock w-8 h-8 />
      {{ countdown }}
    </div>
  </div>
  <div>
    <p>手机玩家请点击屏幕进行操作;</p>
    <p>电脑玩家请通过按键 ↑ ↓ ← → 进行操作;</p>
  </div>
  <div class="app-content" p5>
    <SnakeMap :map="state.map" />
    <SnakeKeyBoard :is-live="isLive" @changeDirection="change" />
  </div>
</template>

<style lang="scss">
html,
body {
  padding: 0;
  overflow: hidden;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.app-content {
  margin: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  position: relative;
}
</style>
